/**
 * 弹出式提示框，默认1.2秒自动消失
 * @param message 提示信息
 * @param style 提示样式，有alert-success、alert-danger、alert-warning、alert-info
 * @param time 消失时间
 */
var prompt = function (message, style, time) {
  style = (style === undefined) ? 'alert-success' : style;
  time = (time === undefined) ? 1200 : time;
  $('<div>')
    .appendTo('body')
    .addClass('alert ' + style)
    .html(message)
    .show()
    .delay(time)
    .fadeOut();
};

// 成功提示
var success_prompt = function (message, time) {
  prompt(message, 'alert-success', time);
};

// 失败提示
var fail_prompt = function (message, time) {
  prompt(message, 'alert-danger', time);
};

// 提醒
var warning_prompt = function (message, time) {
  prompt(message, 'alert-warning', time);
};

// 信息提示
var info_prompt = function (message, time) {
  prompt(message, 'alert-info', time);
};

/**
 * 工具参数，获取queryString
 *
 * @param {*} name
 * @returns
 */
function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return decodeURI(r[2]);
  return null;
}

/**
 * 在当前路由上设置新的query
 *
 * @param {*} key
 * @param {*} value
 */
function setQueryString(obj) {
  var href = window.location.search;
  var searchObj = {};
  var searchArrs = href.slice(1).split('&');
  searchArrs.forEach(function (v, k) {
    searchObj[v.split('=')[0]] = v.split('=')[1];
  });
  _.mapKeys(obj, function (value, key) {
    searchObj[key] = value;
  });
  return window.location.pathname + '?' + Object.keys(searchObj).map(function (v) {
    return v + '=' + searchObj[v];
  }).join('&');
}

/**
 * 在当前路由上改变param
 *
 * @param {*} str
 * @returns
 */
function setParams(str) {
  var pathname = window.location.pathname;
  var pathnameArr = pathname.split('/');
  pathnameArr.pop();
  pathnameArr.push(str);
  return pathnameArr.join('/') + window.location.search;
}

/**
 * 退出登录
 *
 */
function logout() {
  $.get('/api/logout', function(res) {
    history.go(0);
  });
}

$(function () {
  jconfirm.defaults = {
    // theme: 'modern'
    type: 'green',
    theme: 'material'
  };
  /** 
   *  jquery ajax 全局配置
   */
  $.ajaxSetup({
    error: function (res, textStatus) {
      if (res.status === 403) {
        fail_prompt('用户登录信息已过期, 3秒后跳转登录页面', 2000);
        setTimeout(function () {
          window.location = '/login?from=' + encodeURIComponent(window.location.pathname);
        }, 2500);
      } else {
        fail_prompt(_.get(res.responseJSON, 'data') || _.get(res.responseJSON, 'result') || _.get(res.responseJSON, 'msg') || '系统错误!');
      }
    }
  });

  /**
   * jquery 拓展
   */
  $.fn.extend({
    setLoading: function (text, size) {
      var _position = $(this).css('position');
      if (!['relative', 'absolute', 'fixed'].includes(_position)) {
        console.log("position 不为 'relative', 'absolute', 'fixed', 不支持该方法");
        return;
      }
      var _load = $(this).data('loading');
      if (_load === 'loading') {
        console.log('已有loading状态');
        return;
      } else {
        $(this).data('loading', 'loading');
      }
      $(this).append('<div class="loading-container"><div class="loading">' +
        '<div class="loader-box ' + (size ? size : '') + '">' +
        '<div></div>' +
        '<div></div>' +
        '<div></div>' +
        '<div></div>' +
        '<div></div>' +
        '</div>' +
        '<div>' + (text ? text : '') + '</div>' +
        '</div></div>');
    },
    cancelLoading: function () {
      var _load = $(this).data('loading');
      if (_load === 'loading') {
        $(this).data('loading', 'loading');
      } else {
        return;
      }
      $(this).children('.loading-container').remove();
    }
  });

  /** 
   *  bootstrap tooltop 初始化
   */
  $('[data-toggle="tooltip"]').tooltip();

  $('.hover-ani').hover(function (e) {
    $(this).children('span').text('>>').css('padding-left', '6px');
  }, function (e) {
    $(this).children('span').text('>').css('padding-left', '0px');
  });

  $(document).on('click', '.set-query', handleQueryLink)
    .on('click', '.topbar-search-dropdown .dropdown-item', handleSearchClick)
    .on('click', '.topbar-search-btn', handleSearchSubmit)
    .on('click', '.hosiptal-search-btn', handleHospitalSearchSubmit)
    .on('keydown', '.topbar-search-container .topbar-search-ipt', handleSearchKeySubmit)
    .on('mouseover', '.topbar-hot-ks', handleHotDepContainerShow)
    .on('mouseleave', '.topbar-hot-dept-container', handleHotDepContainerHide)
    .on('mouseover', '.home-hot-ks-block', handleHotDepShow)
    .on('mouseleave', '.home-first-bx', handleHotDepHide)
  function handleQueryLink() {
    var query = $(this).data('query');
    if (query === 'searchType') {
      window.location.href = setParams($(this).data('value'));
    } else {
      window.location.href = setQueryString({
        page: 1,
        [query]: $(this).data('value'),
      });
    }
  }

  function handleSearchClick() {
    $(this).parents('.topbar-search-dropdown')
      .children('.dropdown-toggle').text($(this).text())
      .data('id', $(this).data('id'));
  }

  function handleSearchKeySubmit(e) {
    if (e.keyCode === 13) {
      $(this).next().find('button').click();
    }
  }

  function handleSearchSubmit() {
    if (!$(this).parents('.topbar-search-container').find('.topbar-search-ipt').val()) {
      warning_prompt('请输入搜索内容');
      return;
    }
    window.location.href = ('/search/' +
      $(this).parents('.topbar-search-container').find('.dropdown-toggle').data('id') +
      '?page=1&key=' + $(this).parents('.topbar-search-container').find('.topbar-search-ipt').val()
    );
  }

  function handleHospitalSearchSubmit() {
    if (!$(this).parents('.topbar-search-container').find('.topbar-search-ipt').val()) {
      warning_prompt('请输入搜索内容');
      return;
    }
    window.location.href = ('/hospital/' + $(this).data('hos') + '/' +
      $(this).parents('.topbar-search-container').find('.dropdown-toggle').data('id') +
      '?&key=' + $(this).parents('.topbar-search-container').find('.topbar-search-ipt').val()
    );
  }
  // 热门科室
  function handleHotDepContainerShow(e) {
    $('.topbar-hot-dept').css('display', 'block');
    $('.topbar-hot-dept').css('opacity', 1);
  }

  function handleHotDepShow(e) {
    if ($(this).hasClass('home-hot-ks-block-active')) {
      return;
    }
    $('.home-hot-more-ks').html($(this).data('detail'));
    $('.home-hot-ks-block').removeClass('home-hot-ks-block-active');
    $(this).addClass('home-hot-ks-block-active');
    $('.home-hot-more-ks').css('display', 'block');
    $('.home-hot-more-ks').css('opacity', 1);
  }

  function handleHotDepHide(e) {
    if ($('.home-hot-more-ks').css('opacity') == '0') {
      return;
    }
    $('.home-hot-ks-block').removeClass('home-hot-ks-block-active');
    $('.topbar-hot-dept').css('opacity', 0);
    setTimeout(function () {
      $('.topbar-hot-dept').css('display', 'none');
    }, 300);
  }

  function handleHotDepContainerHide(e) {
    setTimeout(function () {

      $('.topbar-hot-dept').css('opacity', 0);
      $('.topbar-hot-dept').css('display', 'none');
    }, 100);
  }

});